/**
 * 本页面中workers和selects的关系 双方不能直接赋值     但是子对象的内存地址相同  因此实现可以快速的使用indexOf
 */
import {
    checkperiodareaApi
} from '../../api/long-insure'
import {
    getPlanInfo,
    getDispatchList,
    addInsure,
    subtractInsure,
    getWorkPlanData,
    getInviteCode,
    getInviteWorkers,
    testingInsure,
    renewalMonthNotify,
    testingIfChoiceDispatch
} from '../../api/long-insure'
import {
    createClientQrCode
} from '../../../api/app'
import {
    dateFormat,
    createQrcode,
    wxfileTobase64
} from '../../../utils/util'
import dayjs from 'dayjs'
const app = getApp()
import user from '../../../utils/user'
Page({
    data: {
        disabledDate({
            day,
            month,
            year
        }) {
            const now = new Date()
            const date = new Date(year, month - 1, day + 1)
            return date < now
        },
        isCalenderUp: false,
        isWhitelist: 0,
        showerror1msg: '',
        showerror1: false,
        moreisopen: false,
        isselectspecialAppoint: false,
        specialAppoint: '',
        date: '',
        workers: [],
        type: '',
        id: '',
        isEdit: false,
        detail: {},
        selects: [],
        dispatchList: [],
        dispatch: {},
        showDispatch: false,
        workType: '',
        workTypes: [],
        isSetWork: false,
        isInvite: false,
        inviteCode: '',
        inviteTime: 0,
        inviteTimeVal: '',
        inviteEndTime: '',
        isSufficient: false,
        currentBalance: Number,
        tomorrowNeedCostFee: Number,
        willEnsureCostFee: Number,
        renew: '',
        pickerDisabled: false,
        isRenew: false,
        isRenewAmount: false,
        staffEchoList: [],
        testingInsureInfo: {},
        isCodePop: false,
        isAgain: false,
        dispatchPop: {},
        workTypePop: '',
        showerror: false,
        showerrorc: false,
        errlist: [],
        changeTime: '',
    },
    getDateList({
        detail
    }) {
        // 检查是否已经获取过该月的数据
        if (this.filterGetList(detail)) {
            // 获取数据
            console.log(detail, '获取数据')
        }
    },
    // 过滤重复月份请求的方法
    filterGetList({
        setYear,
        setMonth
    }) {
        const dateListMap = new Set(this.data.dateListMap)
        const key = `y${setYear}m${setMonth}`
        if (dateListMap.has(key)) {
            return false
        }
        dateListMap.add(key)
        this.setData({
            dateListMap: [...dateListMap],
        })
        return true
    },
    changetime() {
        this.setData({
            changeTime: '2022/1/1',
        })
    },
    // 日期改变的回调
    selectDay({
        detail
    }) {
        console.log(detail, 'selectDay detail')
        this.setData({
            date: dayjs(detail.year + '-' + detail.month + '-' + detail.day).format('YYYY-MM-DD'),
            isCalenderUp: false
        })
    },
    changeisopen(e) {
        let i = e.currentTarget.dataset.i * 1
        if (i === 1) {
            this.setData({
                moreisopen: false
            })
        } else {
            this.setData({
                moreisopen: true
            })
        }
    },
    changespecialAppointstatus(e) {
        console.log(e)
        let i = e.currentTarget.dataset.i * 1
        if (i === 1) {
            this.setData({
                isselectspecialAppoint: false
            })
        } else {
            this.setData({
                isselectspecialAppoint: true
            })
        }
    },
    onUnload() {
        console.log('????没触发啦')
        clearInterval(this.data.inviteTimeVal)
        const key = this.data.type + this.data.id
        console.log(key, 'keykey')
        if (!this.data.workers.length) {
            wx.removeStorageSync(key)
            return
        }
        wx.setStorageSync(key, {
            date: this.data.date,
            data: this.data.workers,
            invite: this.data.inviteCode,
            inviteEndTime: this.data.inviteEndTime
        })
    },
    onHide() {
        clearInterval(this.data.inviteTimeVal)
        const key = this.data.type + this.data.id
        if (!this.data.workers.length) {
            wx.removeStorageSync(key)
            return
        }
        wx.setStorageSync(key, {
            date: this.data.date,
            data: this.data.workers,
            invite: this.data.inviteCode,
            inviteEndTime: this.data.inviteEndTime
        })
    },
    async onLoad(options) {
        console.log(options, 'fgasgsg')
        await user.waitLogin()
        this.setData({
            renew: !!options.renew,
            type: options.type,
            id: options.id,
        })
        await this.onGetInviteWorkers()
        this.setData({
            workers: this.data.workers
        })
        const key = options.type + options.id
        const storage = wx.getStorageSync(key)

        wx.getStorageSync(key)
        // 数据恢复
        if (storage) {
            app.confirm('您有上次未完成操作，是否继续?').then(() => {
                // 需要使用push方法先进行拼接然后清洗重复数据在赋值
                this.data.workers.map((item) => {
                    storage.data.map((ite) => {
                        if (item.name == ite.name) {
                            // 添加属性用来标记相同的对象
                            item.isRepeat = true
                        }
                    })
                })
                this.data.workers.map((item) => {
                    // 通过标记筛选对象
                    if (!item.isRepeat) {
                        storage.data.unshift(item)
                    }
                })
                this.setData({
                    workers: storage.data,
                    inviteCode: storage.invite,
                    inviteEndTime: storage.inviteEndTime,
                })
                if (options.code === 'period_015_gwy') {
                    console.log(222)
                    this.setData({
                        date: dayjs().add(1, 'day').format('YYYY-MM-DD')
                    })
                } else {
                    this.setData({
                        date: storage.date,
                    })
                }
                wx.setStorageSync(key, {
                    date: this.data.date,
                    data: this.data.workers,
                    invite: this.data.inviteCode,
                    inviteEndTime: this.data.inviteEndTime
                })
                // this.onInviteCode(true, 'hide')
                // wx.removeStorageSync(key)
            }, () => {
                // wx.removeStorageSync(key)
            })
        }
        if (options.type === 'add') {
            wx.setNavigationBarTitle({
                title: '加保',
            })
        } else {
            wx.setNavigationBarTitle({
                title: '减保',
            })
        }

        await getPlanInfo({
            planId: options.id,
            month: ''
        }).then(res => {
            // sx保险方案加减保时间限制  period_015_gwy
            if (res.insurCompany === 'period_015_gwy') {
                this.setData({
                    pickerDisabled: true,
                    date: dayjs().add(1, 'day').format('YYYY-MM-DD')
                })
            }
            this.setData({
                detail: res,
                // 即时生效加保生效日期默认今天，其他的明天
                date: res.type === 5 ? dayjs().format('YYYY-MM-DD') : dayjs().add(1, 'day').format('YYYY-MM-DD')
            })
        })

        if (options.renew) {
            this.renewEcho()
            this.onNextMonth()
        }

    },
    onChangeDate() {
        if (this.data.detail.insurCompany === 'period_015_gwy') {
            wx.showToast({
                title: '此方案加保时间不可修改',
                icon: 'none'
            })
            return
        }
        this.setData({
            isCalenderUp: true
        })
    },
    // 选择生效日期
    onDate(event) {
        this.setData({
            date: event.detail.value
        })
    },
    // 手动添加人员
    onManualAdd() {
        wx.navigateTo({
            url: '/packageLongInsure/pages/worker-add/worker-add?type=' + this.data.type + '&back=manual' + '&insur=' + this.data.detail.insurCompany + '&plancode=' + this.data.detail.insurCompanyPlanCode + '&planId=' + this.data.id,
            events: {
                complete: async (event) => {
                    if (this.filter([event]).length === 0) {
                        app.toast('该员工已存在')
                        return
                    }
                    if (this.data.type === 'subtract') {
                        await this.checkWorker([{
                            userName: event.name,
                            idCardNo: event.idcard
                        }])
                    } else {
                        this.data.workers.push(event)
                    }
                    this.setData({
                        workers: this.data.workers
                    })
                    // 这里监听到 手动添成功 则本地存储一下
                    const key = this.data.type + this.data.id
                    wx.setStorageSync(key, {
                        date: this.data.date,
                        data: this.data.workers,
                        invite: this.data.inviteCode,
                        inviteEndTime: this.data.inviteEndTime
                    })
                    wx.navigateBack()
                }
            }
        })
    },
    // 在线选择人员加入
    // type=subtract&id=17 + this.data.id
    onSelectAdd() {
        wx.navigateTo({
            url: '/packageLongInsure/pages/worker-list/worker-list?type=checkbox&back=manual&date=' + (this.data.type == 'subtract' ? ('&id=' + this.data.id) : '') + '&company=' + this.data.detail.insurCompany + '&status=2',
            events: {
                complete: async (event) => {
                    // 格式化
                    event = event.map(item => ({
                        name: item.userName,
                        idcard: item.idCardNo,
                    }))

                    // 去重复员工
                    const length = event.length
                    event = this.filter(event)

                    // 加减保不同添加员工过程
                    if (this.data.type === 'subtract') {
                        await this.checkWorker(event.map(item => ({
                            userName: item.name,
                            idCardNo: item.idcard
                        })))
                    } else {
                        this.data.workers.push(...event)
                    }
                    this.setData({
                        workers: this.data.workers
                    })
                    wx.navigateBack()
                    // 重复员工提示在回到界面后弹出
                    if (length > event.length) {
                        app.toast('添加成功，有' +
                            (length - event.length) +
                            '条数据重复已去除')
                    }
                    // 这里监听到 在线选择成功 则本地存储一下
                    const key = this.data.type + this.data.id
                    wx.setStorageSync(key, {
                        date: this.data.date,
                        data: this.data.workers,
                        invite: this.data.inviteCode,
                        inviteEndTime: this.data.inviteEndTime
                    })
                }
            }
        })
    },
    // 编辑
    onEdit() {
        this.setData({
            isEdit: true
        })
    },
    // 完成编辑
    onEditComplete() {
        this.setData({
            isEdit: false
        })
    },
    // 选中（取消）某人
    onSelect(event) {
        const index = event.currentTarget.dataset.index
        console.log(this.data.workers, 'workers')
        console.log(this.data.workers[index], '工具下标拿到的数据')
        const worker = this.data.workers[index]
        console.log(this.data.selects, 'selects')
        const indexed = this.data.selects.indexOf(worker)
        console.log(indexed, '判断')
        if (indexed === -1) {
            this.data.selects.push(worker)
        } else {
            this.data.selects.splice(indexed, 1)
        }
        this.setData({
            selects: this.data.selects
        })
    },
    // 选择全部
    onSelectAll() {
        if (this.data.selects.length !== this.data.workers.length) {
            this.data.selects = []
            this.data.selects.push(...this.data.workers)
            this.setData({
                selects: this.data.selects
            })
        } else {
            this.setData({
                selects: []
            })
        }
    },
    // 删除列表中的人员
    onDelSelect() {
        this.data.selects.forEach(item => {
            const index = this.data.workers.indexOf(item)
            this.data.workers.splice(index, 1)
        })
        this.setData({
            selects: [],
            workers: this.data.workers
        })
    },
    // 二维码前置弹窗,选择被派遣单位
    onDispatchEnterPop(event) {
        if (event.currentTarget.dataset.isdisabled) {
            wx.showToast({
                title: '已禁用',
                icon: 'none'
            })
            return
        }
        const index = event.currentTarget.dataset.index
        const dispatchPop = this.data.dispatchList[index]
        if (!dispatchPop.occupationList.length) {
            wx.showModal({
                title: '提示',
                content: '很抱歉，您当前所选择派遣单位的可用工种，不在该方案的承保范围内，请联系您的专属客户经理。',
                showCancel: false
            })
        }
        this.setData({
            dispatchPop: dispatchPop,
            workTypePop: '',
            showDispatch: false,
        })
    },
    // 二维码前置弹窗点击选择工种
    onWorkTypeEnterPop() {
        this.setData({
            workTypesPop: this.data.dispatchPop.occupationList,
        })
    },
    // 二维码前置弹窗选择工种
    onWorkTypePopChoice(event) {
        const index = event.currentTarget.dataset.index
        this.setData({
            workTypesPop: [],
            workTypePop: this.data.workTypesPop[index]
        })
    },
    // 点击被派遣单位，获取被派遣单位列表
    async onDispatch() {
        const result = await getDispatchList({
            pageNum: 1,
            pageSize: 100,
            status: 1,
            insurCompany: this.data.detail.insurCompany,
            planCode: this.data.detail.insurCompanyPlanCode,
            isGetArea: 1
        })
        this.setData({
            dispatchList: result.list,
            showDispatch: true,
            workTypes: false
        })
    },
    // 选择被派遣单位
    async onDispatchEnter(event) {
        let res = await checkperiodareaApi({
            planId: this.data.id
        })
        if (event.currentTarget.dataset.isdisabled) {
            wx.showToast({
                title: '已禁用',
                icon: 'none'
            })
            return
        }
        // if (this.data.detail.insurCompany === 'period_006_gyas' && event.currentTarget.dataset.area === '天津') {
        if (!res.isWhitelist && event.currentTarget.dataset.area === '天津' && this.data.detail.insurCompany === 'period_006_gyas') {
            wx.showToast({
                title: '抱歉，当前方案不支持该（天津）地区投保',
                icon: 'none'
            })
            return
        }
        const index = event.currentTarget.dataset.index
        // const text  = event.currentTarget.dataset.text
        const text = '1、仅承保视频中的对应风险等级工种，其它工种请再提供视频确认2、超风险投保警示:严格按照实际工种对应风险等级进行投保，严禁超风险投保，否则保险公司有权拒赔。如将4类及以上工种投保至1-3类工种属于超风险投保工种'
        let w = text?.length * 24
        if (w > 520) {
            this.setData({
                showmore: true
            })
        } else {
            this.setData({
                showmore: false
            })
        }
        const dispatch = this.data.dispatchList[index]
        console.log(!dispatch.occupationList.length, 'hfashjfsahj')
        if (!dispatch.occupationList.length) {
            wx.showModal({
                title: '提示',
                content: '很抱歉，您当前所选择派遣单位的可用工种，不在该方案的承保范围内，请联系您的专属客户经理。',
                showCancel: false
            })
        }
        this.setData({
            dispatch: dispatch,
            dispatchList: [],
            workType: '',
            specialAppoint: text,
            showDispatch: false,
        })
        // this.setData({
        //     dispatchList: result.list
        // })
    },
    // 点击工种，展示工种列表
    onWorkType() {
        this.setData({
            workTypes: this.data.dispatch.occupationList
        })
    },
    // 选择工种
    onWorkTypeEnter(event) {
        const index = event.currentTarget.dataset.index
        this.setData({
            workTypes: [],
            workType: this.data.workTypes[index]
        })
    },
    // 前往设置被派遣单位
    onGoDispatch() {
        wx.navigateTo({
            url: '/packageLongInsure/pages/dispatch/dispatch',
        })
    },
    // 设置工种
    onSetWork() {
        this.setData({
            isSetWork: true
        })
    },
    // 取消设置工种
    onCancelSetWork() {
        this.setData({
            isSetWork: false,
            dispatch: {},
            showDispatch: false,
            workType: '',
            workTypes: [],
        })
    },
    // 设置工种
    onSubmitWorkType() {
        if (this.data.specialAppoint && !this.data.isselectspecialAppoint) {
            wx.showToast({
                title: '请勾选特别约定',
                icon: 'none'
            })
            return
        }
        this.data.selects.forEach(item => {
            item.dispatch = this.data.dispatch
            item.workType = this.data.workType
            item.specialAppoint = this.data.specialAppoint
        })
        app.toast('设置成功')
        this.onCancelSetWork()
        this.setData({
            selects: [],
            workers: this.data.workers
        })
    },
    async checkWorker(workers) {
        const result = await getWorkPlanData({
            companyPlanId: this.data.id,
            workerInfoList: workers
        })
        if (result.errorList.length) {
            app.toast(`员工${result.errorList[0].userName}${result.errorList[0].errMsg}`)
            throw 'Error'
        }
        this.data.workers.push(...result.correctList.map(item => ({
            name: item.userName,
            idcard: item.idCardNo,
            id: item.id
        })))
        return result.correctList
    },
    async onSubmitAdd() {
        if (!this.data.workers.length) {
            app.toast('请添加需要加保的员工')
            return
        }
        for (let index in this.data.workers) {
            if (!this.data.workers[index]?.workType?.id) {
                app.toast('请为员工' + this.data.workers[index].name + '设置工种')
            }
        }
        if (!this.data.date) {
            app.toast('请选择加保日期')
            return
        }
        const result = await addInsure({
            companyPlanId: this.data.id,
            insurStartDay: this.data.date,
            staffList: this.data.workers.map(item => ({
                userName: item.name,
                idCardNo: item.idcard,
                serveCompanyName: item.dispatch.serveCompanyName,
                occupationName: item.workType.name,
                serveCompanyId: item.dispatch.serveCompanyId,
                occupationId: item.workType.id
            }))
        })
        this.setData({
            isRenew: false
        })
        if (result.code === 2) {
            console.log(result, 'resultresultresultresultresultresult')
            this.setData({
                showerror1: true,
                showerror1msg: result.msg
            })
            return
        }
        if (result.code === 1 && result.errorList.length > 0) {
            console.log(result, 'resultresultresultresultresultresult')
            this.setData({
                showerror: true,
                errlist: result.errorList
            })
            return
        }
        if (result.code && result?.code === 1) {
            app.toast(result.data)
            return
        }
        if (result.isSuccess === false && !result.isEnoughBalance) {
            this.setData({
                isSufficient: true,
                currentBalance: result.currentBalance,
                tomorrowNeedCostFee: result.tomorrowNeedCostFee,
                willEnsureCostFee: result.willEnsureCostFee
            })
            return
        }
        // 清除员工列表，防止暂存
        const length = this.data.workers.length
        this.data.workers = []
        // 清除 本地缓存
        wx.removeStorageSync(this.data.type + this.data.id)
        if (result.isSuccess) {
            wx.redirectTo({
                url: '/pages/success/success?title=加保成功&content=本次加保共' + length + '人，生效日期为' + this.data.date,
            })
        }

    },
    popsureorderc() {
        this.data.errlist.forEach((ele, index) => {
            this.data.workers.forEach((j, i) => {
                if (ele.idCardNo === j.idcard) {
                    this.data.workers.splice(i, 1)
                }
            })
        })
        console.log(this.data.workers)
        if (this.data.workers.length !== 0) {
            this.onSubmitAdd()
        } else {
            this.setData({
                workers: []
            })
            wx.showToast({
                icon: 'none',
                title: '投保人数为0，不允许投保。',
            })
        }

    },
    popsureorder() {
        this.setData({
            showerror: false,
            showerrorc: true,
        })
    },
    popsureorder1() {
        this.setData({
            showerror1: false,
        })
        wx.redirectTo({
            url: '/packageLongInsure/pages/index/index',
        })
    },
    popcancelorder() {
        this.setData({
            showerror: false,
        })
    },
    popcancelorder1() {
        this.setData({
            showerror1: false,
        })
    },
    popcancelorderc() {
        this.setData({
            showerrorc: false,
        })
    },
    async onSubmitSubtract() {
        if (!this.data.workers.length) {
            app.toast('请添加需要减保的员工')
            return
        }
        if (!this.data.date) {
            app.toast('请选择减保日期')
            return
        }
        await subtractInsure({
            insurEndDay: this.data.date,
            ids: this.data.workers.map(item => item.id),
            companyPlanId: this.data.id
        })
        // 清除员工列表，防止暂存
        const length = this.data.workers.length
        this.data.workers = []
        wx.redirectTo({
            url: '/pages/success/success?title=减保成功&content=本次减保共' + length + '人，生效日期为' + this.data.date,
        })
    },
    // 去重
    filter(workers) {
        // 与已经存在的数据去重
        workers = workers.filter(item => {
            for (const index in this.data.workers) {
                if (this.data.workers[index].idcard === item.idcard) {
                    return false
                }
            }
            return true
        })
        // 与已经自身去重
        let num = 0
        return workers.filter(item => {
            num = 0
            for (const ite of workers) {
                if (ite.idcard === item.idcard) {
                    if (num === 0) {
                        num += 1
                    } else {
                        return false
                    }
                }
            }
            return true
        })
    },
    onReInviteCode() {
        // 重新发起小程序的时候 先隐藏二维码弹窗 在弹出 选择派遣单位 弹窗，只有在选择完派遣单位并且点击确定后在调用onInviteCode方法
        this.setData({
            isAgain: true,
            isInvite: false,
            isCodePop: true
        })

    },
    async onInviteCode(isOld = false, isHide = false) {
        clearInterval(this.data.inviteTimeVal)
        const result = await getInviteCode({
            companyPlanId: this.data.id,
            codeType: this.data.type === 'add' ? 0 : 1,
            generate: typeof isOld === 'boolean' ? !isOld : false,
            serveCompanyId: this.data.dispatchPop.serveCompanyId ? this.data.dispatchPop.serveCompanyId : '',
            serveCompanyName: this.data.dispatchPop.serveCompanyName ? this.data.dispatchPop.serveCompanyName : '',
            occupationId: this.data.workTypePop.id ? this.data.workTypePop.id : '',
            occupationName: this.data.workTypePop.name ? this.data.workTypePop.name : ''
        })
        let scene = ''
        scene = 'LIKey=' + result.key + '&Id=' + this.data.id
        console.log(scene, 'scene')

        const text = app.globalData.qrCodeUrl + '?qrcodeType=normal&scene=' + encodeURIComponent(scene)

        const res = await createQrcode('qrcode', text)
        const base64 = await wxfileTobase64(res)
        // let base64 = await createClientQrCode({
        //     page: 'pages/join/join',
        //     scene: scene,
        //     width: 280
        // })
        console.log(scene, 'scene')
        if (!isHide) {
            this.setData({
                isInvite: true,
            })
        }
        this.setData({
            inviteCode: 'data:image/jpeg;base64,' + base64,
            inviteTime: result.time,
            inviteTimeVal: setInterval(() => {
                this.setData({
                    inviteTime: this.data.inviteTime - 1
                })
                if (this.data.inviteTime === 0) {
                    this.onInviteCode(false, !this.data.isInvite)
                } else if (this.data.inviteTime % 5 === 0) { // 每5秒拉一次人员
                    getInviteWorkers({
                        companyPlanId: this.data.id,
                        codeType: this.data.type === 'add' ? 0 : 1,
                    }).then(async res => {
                        let workers = this.filter(res.map(item => ({
                            idcard: item.idCardNo,
                            name: item.userName,
                            dispatch: {
                                serveCompanyName: item.serveCompanyName,
                                serveCompanyId: item.serveCompanyId
                            },
                            workType: {
                                name: item.occupationName,
                                id: item.occupationId
                            }
                        })))
                        if (workers.length === 0) {
                            return
                        }
                        if (this.data.type === 'subtract') {
                            await this.checkWorker(workers.map(item => {
                                return {
                                    userName: item.name,
                                    idCardNo: item.idcard
                                }
                            }))
                        } else {
                            this.data.workers.push(...workers)
                        }
                        this.setData({
                            workers: this.data.workers
                        })

                    })
                }
            }, 1000)
        })
    },
    // 该方法仅进入页面调用一次，原因是因为 需要看看后端哪里有没有 存储数据 如果有存储则显示到页面上 
    onGetInviteWorkers() {
        getInviteWorkers({
            companyPlanId: this.data.id,
            codeType: this.data.type === 'add' ? 0 : 1,
        }).then(async res => {
            let workers = this.filter(res.map(item => ({
                idcard: item.idCardNo,
                name: item.userName,
                dispatch: {
                    serveCompanyName: item.serveCompanyName,
                    serveCompanyId: item.serveCompanyId
                },
                workType: {
                    name: item.occupationName,
                    id: item.occupationId
                }
            })))
            if (workers.length === 0) {
                return
            }
            if (this.data.type === 'subtract') {
                await this.checkWorker(workers.map(item => {
                    return {
                        userName: item.name,
                        idCardNo: item.idcard
                    }
                }))
            } else {
                this.data.workers.push(...workers)
            }
            this.setData({
                workers: this.data.workers
            })
            clearInterval(this.data.inviteTimeVal)
            const key = this.data.type + this.data.id
            wx.setStorageSync(key, {
                date: this.data.date,
                data: this.data.workers,
                invite: this.data.inviteCode,
                inviteEndTime: this.data.inviteEndTime
            })
        })
    },
    onCancelInviteCode() {
        this.setData({
            isInvite: false
        })
    },
    onSufficient() {
        this.setData({
            isSufficient: false
        })
    },
    //  获取下个月
    async onNextMonth() {
        const time = new Date()
        const year = time.getFullYear()
        const month = time.getMonth() + 2
        console.log(2121, year)
        console.log(3333, month)
        console.log(dayjs().add(1, 'month').startOf('month').format('YYYY-MM-DD'))
        this.setData({
            date: dayjs().add(1, 'month').startOf('month').format('YYYY-MM-DD'), // dateFormat('YYYY-mm', new Date((month == 13 ? year + 1 : year) + '-' + (month == 13 ? '01' : month))) + '-01',
            pickerDisabled: true
        })
    },
    // 检测加保
    async onTestingInsure() {
        const result = await testingInsure({
            companyPlanId: this.data.id,
            insurStartDay: this.data.date,
            staffList: this.data.workers.map(item => ({
                userName: item.name,
                idCardNo: item.idcard,
                serveCompanyName: item.dispatch.serveCompanyName,
                occupationName: item.workType.name,
                serveCompanyId: item.dispatch.serveCompanyId,
                occupationId: item.workType.id
            }))
        })
        this.setData({
            isRenew: result.isSuccess,
            isRenewAmount: !result.isSuccess,
            testingInsureInfo: result
        })
    },
    // 人员数据回显
    async renewEcho() {
        const result = await renewalMonthNotify({
            planId: this.data.id
        })
        const arr = result.staffList.map(item => {
            return {
                name: item.userName,
                idcard: item.idCardNo,
                dispatch: {
                    serveCompanyName: item.serveCompanyName,
                    serveCompanyId: item.serveCompanyId
                },
                workType: {
                    name: item.occupationName,
                    id: item.occupationId
                }
            }
        })
        this.setData({
            workers: arr
        })
        // this.setData({
        //     staffEchoList:result.staffList
        // })
    },
    // 检测投保取消
    onSestingCancel() {
        this.setData({
            isRenew: false,
        })
    },
    // 余额不足弹窗关闭
    onTestingBalance() {
        this.setData({
            isRenewAmount: false,
        })
    },
    // 检测
    async testingIfChoiceDispatch() {
        return await testingIfChoiceDispatch({
            companyPlanId: this.data.id,
            codeType: 0
        })

    },
    // 二维码邀请前选择派遣单位选择弹窗取消事件
    onCodePopCancel() {
        this.setData({
            isAgain: false,
            isCodePop: false,
        })
    },
    // 二维码邀请前选择派遣单位选择弹窗确定事件
    onCodePopDefine() {
        if (!this.data.dispatchPop.id) {
            app.toast('请选择派遣单位')
            return
        }
        if (!this.data.workTypePop.id) {
            app.toast('请选择工种')
            return
        }
        this.setData({
            isCodePop: false,
            isAgain: false
        })
        clearInterval(this.data.inviteTimeVal)
        this.onInviteCode()
    },
    async onInviteCodeFront() {
        // 先调用一个接口来判断是否可以 出现弹窗 如果 不能出现则调用 onInviteCode 方法
        if (this.data.isAgain) {
            this.setData({
                isAgain: false
            })
            clearInterval(this.data.inviteTimeVal)
            this.onInviteCode(false)
        }
        const result = await this.testingIfChoiceDispatch()
        if (result.code == 1) {
            this.setData({
                isCodePop: true
            })
        } else if (result.code == 0) {
            this.onInviteCode(true)
        }
    },
    // 清洗数据 方法
    getClean() {
        const key = this.data.type + this.data.id
        const storage = wx.getStorageSync(key)
        // 格式化
        storage.data = storage.data.map(item => ({
            idcard: item.idCardNo,
            name: item.userName,
            dispatch: {
                serveCompanyName: item.serveCompanyName,
                serveCompanyId: item.serveCompanyId
            },
            workType: {
                name: item.occupationName,
                id: item.occupationId
            }
        }))
        this.setData({
            workers: storage.data,
            date: storage.data,
            inviteCode: storage.invite,
            inviteEndTime: storage.inviteEndTime,
        })
    }

})